import { type Ref, onUnmounted, ref } from "vue";
// 独立瓦片层工厂
import TileLayers from "@/utils/tile-layers";
import L from "leaflet";
import { mapConfig } from "@/config/map";

// type TileProvider = Parameters<(typeof TileLayers)[keyof typeof TileLayers]>[0];
export type TileProvider = keyof typeof TileLayers | "custom";
// type TileProvider = "geoq" | "baidu" | "gaode" | "custom";
type MapConfig = {
  center?: L.LatLngExpression;
  zoom?: number;
  tileType?: TileProvider;
  isMousePosition?: boolean;
  tileOptions?: Record<string, any>;
};

export function useMap(containerRef: Ref<HTMLElement>, config: MapConfig = {}) {
  const map = ref<L.Map | null>(null);
  // 初始化地图
  const initMap = async () => {
    if (!containerRef.value) return;

    map.value = L.map(containerRef.value, {
      ...config,
      center: config.center || mapConfig.center,
      zoom: config.zoom || mapConfig.zoom,
      crs: L.CRS.EPSG3857 // 高德标准坐标系
    });
    // 动态加载瓦片层
    loadTileLayer(config.tileType || "geoq", config.tileOptions);

    // 添加控件（比例尺、鼠标位置等）
    L.control.scale().addTo(map.value);
    // 设置地图视角位置
    map.value.setView([39.9042, 116.4074], 12);
    config?.isMousePosition && addMousePositionByMap(map.value);

    // 监听地图加载完成
    map.value.on("load", () => {
      console.log("地图加载完成");
    });
    // 生命周期管理
    // onUnmounted(() => {
    //   console.log("清理地图资源 useMap");
    //   // 清理地图资源
    //   if (map.value) {
    //     map.value?.remove();
    //     map.value = null;
    //   }
    // });
  };
  // 监听窗口大小变化，调整地图
  window.addEventListener("resize", () => {
    if (map.value) map.value.invalidateSize();
  });

  // 动态切换瓦片层
  const loadTileLayer = async (type: TileProvider, options?: any) => {
    console.log("动态切换瓦片层", type, options);
    const tileLayer = await tileLayerFactory(type, options);
    // 移除默认图层，添加高德/其他地图矢量图层
    map.value?.eachLayer(l => map.value?.removeLayer(l));
    tileLayer?.addTo(map.value);
  };

  // 新增视角控制方法
  const setView = (center: L.LatLngExpression, zoom: number) => {
    map.value?.setView(center, zoom);
  };

  return { map, initMap, setView, loadTileLayer };
}

async function tileLayerFactory(
  type: TileProvider,
  options: any
): L.TileLayer | null {
  if (type === "custom") {
    return L.tileLayer(options.url, options);
  }
  const creator: any = TileLayers[type];
  return creator ? creator(options.type, options.layerOptions) : null;
}
/**
 * 在地铁上展示鼠标点位经纬度信息
 * @param map 地图实例
 */
export function addMousePositionByMap(map: any) {
  const position = "bottomright";
  L.control
    .mousePosition({
      position,
      lngFirst: true,
      separator: " / ",
      lngFormatter(val: number) {
        return "经度:" + val.toFixed(6);
      },
      latFormatter(val: number) {
        return "纬度:" + val.toFixed(6);
      }
    })
    .addTo(map);
}
